package ase.assignment.sts.ws.impl;

import java.rmi.RemoteException;
import java.util.Date;

import ase.assignment.sts.api.CommonHandler;
import ase.assignment.sts.api.StockHandler;
import ase.assignment.sts.beans.StockAssertEntity;
import ase.assignment.sts.beans.StockQuoteEntity;
import ase.assignment.sts.ws.beans.WSUtil;
import ase.assignment.sts.ws.stock.StockPortType;
import ase.assignment.sts.ws.stock.StockServiceLocator;

public class StockHandlerWSImpl implements StockHandler {
	private StockPortType portType;

	StockHandlerWSImpl() {
		try {
			portType = new StockServiceLocator().getSTSStock();
		} catch (javax.xml.rpc.ServiceException jre) {
			if (jre.getLinkedCause() != null)
				jre.getLinkedCause().printStackTrace();
		}
	}

	public void create(StockAssertEntity stock) {
		try {
			portType.create(WSUtil.convert(stock));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void delete(int stockId) {
		try {
			portType.delete(stockId);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public StockAssertEntity findById(int stockId) {
		try {
			return WSUtil.convert(portType.findById(stockId));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public StockAssertEntity[] getAllStocks(int porId) {
		try {
			ase.assignment.sts.ws.beans.StockAssertEntity[] entities = portType
					.getAllStocks(porId);
			if (entities != null) {
				StockAssertEntity[] beans = new StockAssertEntity[entities.length];
				for (int i = 0; i < entities.length; i++) {
					beans[i] = WSUtil.convert(entities[i]);
				}
				return beans;
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public StockQuoteEntity getCurrentPrice(int stockId) {
		StockQuoteEntity quote = new StockQuoteEntity(stockId);
		StockAssertEntity asserts = findById(stockId);
		quote.setTime(new Date());
		if (asserts != null) {
			double price = CommonHandler.calculateQuote(asserts.getInitPrice());
			quote.setPrice(price);
		}
		return quote;
	}

	public void update(StockAssertEntity stock) {
		try {
			portType.update(WSUtil.convert(stock));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

}
